package com.hson.demo.soa.service.thread;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;

import com.hson.demo.base.util.CollectionUtil;
import com.hson.demo.soa.dao.activity.ActivityRecordDAO;
import com.hson.demo.soa.dto.activity.TestDTO;

/**
 * 大转盘添加抽奖记录，抽奖时与主任务异步执行
 * @author:chenhs E-mail:hson08_chen@163.com
 * Created on 2017年5月24日 下午12:06:43
 */
public class ActivityRecordThread extends AbstractSoaThread {

	private ActivityRecordDAO activityRecordDAO;
	
	// 队列
	private List<TestDTO> queue = new ArrayList<TestDTO>();
	
	
	public void setActivityRecordDAO(ActivityRecordDAO activityRecordDAO) {
		this.activityRecordDAO = activityRecordDAO;
	}


	//增加执行任务数据
	public synchronized void addActivityRecord(TestDTO obj) {
		synchronized (queue) {
			queue.add(obj);
			notify();
		}
	}


	@Override
	public void run() {
		while(true){
			synchronized (queue) {
				if(!CollectionUtil.isEmpty(queue)){
					Iterator<TestDTO> it = queue.iterator();
					while(it.hasNext()){
						try {
							TestDTO element = it.next();
							activityRecordDAO.insert(element);
							
							it.remove();
							sleep(500L);
						} catch (ConcurrentModificationException cme) {
							//
						} catch (IllegalStateException ise) {
							//
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						try {
							sleep(1000L);
						} catch (Exception e) {
							// TODO: handle exception
						}
						
					}
				}
			}
		}
	}
	
	
	
}
